#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# config_adapter.py - 配置文件适配器

import json
import os
from typing import Dict, Any


class ConfigAdapter:
    """配置适配器，用于处理新旧配置格式的转换"""
    
    def __init__(self, config_path: str = None):
        """
        初始化配置适配器
        
        Args:
            config_path: 配置文件路径，默认为UI目录下的config.json
        """
        if config_path is None:
            # 默认使用UI目录下的config.json
            # 从 backend/core/detectidentify/web/ 回到项目根目录，然后到 UI/
            current_dir = os.path.dirname(__file__)  # backend/core/detectidentify/web/
            backend_dir = os.path.dirname(os.path.dirname(os.path.dirname(current_dir)))  # backend/
            project_root = os.path.dirname(backend_dir)  # 项目根目录
            self.config_path = os.path.join(project_root, 'UI', 'config.json')
        else:
            self.config_path = config_path
        
        self.config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            print(f"配置文件未找到: {self.config_path}")
            return self._get_default_config()
        except json.JSONDecodeError as e:
            print(f"配置文件格式错误: {e}")
            return self._get_default_config()
    
    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            "providers": {
                "local": {
                    "type": "ollama",
                    "api_url": "http://localhost:11434",
                    "chat_endpoint": "/v1/chat/completions",
                    "model": "qwen7b:latest"
                }
            },
            "current_provider": "local",
            "temperature": 0.7,
            "max_tokens": 1024
        }
    
    def get_current_provider_config(self) -> Dict[str, Any]:
        """获取当前提供商的配置"""
        current_provider = self.config.get("current_provider", "local")
        providers = self.config.get("providers", {})
        
        if current_provider not in providers:
            print(f"警告: 提供商 '{current_provider}' 不存在，使用默认提供商 'local'")
            current_provider = "local"
        
        return providers.get(current_provider, {})
    
    def get_api_url(self) -> str:
        """获取API URL"""
        provider_config = self.get_current_provider_config()
        api_url = provider_config.get("api_url", "http://localhost:11434")
        chat_endpoint = provider_config.get("chat_endpoint", "/v1/chat/completions")
        
        # 如果API URL已经包含完整路径，直接返回
        if chat_endpoint.startswith("http"):
            return chat_endpoint
        
        # 否则拼接API URL和chat endpoint
        if api_url.endswith("/"):
            return f"{api_url}{chat_endpoint.lstrip('/')}"
        else:
            return f"{api_url}{chat_endpoint}"
    
    def get_api_key(self) -> str:
        """获取API密钥"""
        provider_config = self.get_current_provider_config()
        return provider_config.get("api_key", "")
    
    def get_model(self) -> str:
        """获取模型名称"""
        provider_config = self.get_current_provider_config()
        return provider_config.get("model", "qwen7b:latest")
    
    def get_temperature(self) -> float:
        """获取温度参数"""
        return self.config.get("temperature", 0.7)
    
    def get_max_tokens(self) -> int:
        """获取最大token数"""
        return self.config.get("max_tokens", 1024)
    
    def get_provider_type(self) -> str:
        """获取提供商类型"""
        provider_config = self.get_current_provider_config()
        return provider_config.get("type", "ollama")
    
    def is_openai_compatible(self) -> bool:
        """判断是否为OpenAI兼容的API"""
        provider_type = self.get_provider_type()
        return provider_type in ["openai", "deepseek", "ollama"]
    
    def get_authorization_header(self) -> Dict[str, str]:
        """获取授权头"""
        api_key = self.get_api_key()
        if api_key:
            return {"Authorization": f"Bearer {api_key}"}
        return {}
    
    def validate_config(self) -> bool:
        """验证配置是否有效"""
        try:
            # 检查必要的配置项
            if not self.config.get("providers"):
                print("错误: 缺少providers配置")
                return False
            
            current_provider = self.get_current_provider_config()
            if not current_provider:
                print("错误: 当前提供商配置无效")
                return False
            
            # 检查API URL
            api_url = self.get_api_url()
            if not api_url:
                print("错误: API URL配置无效")
                return False
            
            print(f"配置验证通过 - 当前提供商: {self.config.get('current_provider')}")
            print(f"API URL: {api_url}")
            print(f"模型: {self.get_model()}")
            
            return True
        except Exception as e:
            print(f"配置验证失败: {e}")
            return False


if __name__ == "__main__":
    # 测试配置适配器
    adapter = ConfigAdapter()
    
    print("配置适配器测试:")
    print(f"API URL: {adapter.get_api_url()}")
    print(f"模型: {adapter.get_model()}")
    print(f"温度: {adapter.get_temperature()}")
    print(f"最大Token: {adapter.get_max_tokens()}")
    print(f"提供商类型: {adapter.get_provider_type()}")
    print(f"OpenAI兼容: {adapter.is_openai_compatible()}")
    
    adapter.validate_config()
